package cn.jdemo.io.util;

import java.io.*;

/**
 * 输出流
 * @see java.io.ObjectOutputStream
 * @see java.io.ObjectOutputStream#ObjectOutputStream(OutputStream)
 * @see java.io.ObjectOutputStream#ObjectOutputStream()
 *
 * @see java.io.ByteArrayOutputStream#toByteArray() 此输出流的当前内容，以字节数组形式
 *
 * 输入流
 * @see java.io.ObjectInputStream
 * @see java.io.ObjectInputStream#ObjectInputStream(InputStream)
 * @see java.io.ObjectInputStream#ObjectInputStream()
 *
 * @see java.io.ByteArrayInputStream#ByteArrayInputStream(byte[] buf) 输入缓冲区数据
 *
 * @description
 * @date 2020/12/24
 */
public class CloneUtil {

    public static <T>T clongObj(T t){
        ObjectOutputStream objectOS = null;
        ObjectInputStream objectIS = null;
        try {
            // 输出到流
            ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
            objectOS = new ObjectOutputStream(byteArrayOS);
            objectOS.writeObject(t);

            // 输入流
            objectIS = new ObjectInputStream(new ByteArrayInputStream(byteArrayOS.toByteArray()));
            return (T) objectIS.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                objectOS.close();
                objectIS.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {

    }

}
